package ru.vsu.cs.kis.elections.server.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import ru.vsu.cs.kis.elections.server.ServerConsts;
import ru.vsu.cs.kis.elections.server.dao.CandidateDao;
import ru.vsu.cs.kis.elections.server.dao.PrecinctDao;

public class DBConnector {

	private static CandidateDao candidateDao;

	private static PrecinctDao precinctDao;

	private static Connection con;

	public static boolean connect() {
		try {
			Class.forName(ServerConsts.DB_DRIVER);
			con = DriverManager.getConnection(ServerConsts.DB_URL, ServerConsts.DB_USER,
					ServerConsts.DB_PASSWORD);
			candidateDao = new CandidateDao(con);
			precinctDao = new PrecinctDao(con);
			return true;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static boolean disconnect() {
		try {
			con.close();
			candidateDao = null;
			precinctDao = null;
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static CandidateDao getCandidateDao() {
		if (con == null) {
			System.out.println("Disconnected.");
			return null;
		} else if (candidateDao != null) {
			return candidateDao;
		} else {
			return new CandidateDao(con);
		}
	}

	public static PrecinctDao getPrecinctDao() {
		if (con == null) {
			System.out.println("Disconnected.");
			return null;
		} else if (candidateDao != null) {
			return precinctDao;
		} else {
			return new PrecinctDao(con);
		}
	}

	public static boolean isConnected() {
		try {
			return con.isValid(0);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
}
